<template>
	<view class="classify-container">
		<!-- 搜索组件 -->
		<mysearch @search="handleSearch"></mysearch>

		<!-- 分类内容区域 -->
		<view class="content-layout">
			<!-- 左侧分类导航 (3:7比例) -->
			<scroll-view class="category-sidebar" scroll-y="true">
				<view v-for="category in categories" :key="category.id"
					:class="['category-item', activeCategory === category.id ? 'active' : '']"
					@click="selectCategory(category.id)">
					<text class="category-name">{{ category.name }}</text>
				</view>
			</scroll-view>

			<!-- 右侧菜品展示 -->
			<scroll-view class="dish-content" scroll-y="true" @scrolltolower="loadMore">
				<!-- 分类标题 -->
				<view class="section-header" v-if="activeCategoryName">
					<text class="section-title">{{ activeCategoryName }}</text>
				</view>

				<!-- 菜品列表 -->
				<view class="dish-grid">
					<view v-for="dish in dishes" :key="dish.id" class="dish-card" @click="viewDishDetail(dish)">
						<image :src="dish.image || '/static/default-dish.png'" mode="aspectFill" class="dish-image"
							lazy-load></image>
						<view class="dish-info">
							<text class="dish-name">{{ dish.name }}</text>
							<text class="dish-desc" v-if="dish.description">{{ dish.description }}</text>
							<view class="dish-bottom">
								<text class="dish-price">¥{{ dish.price }}</text>
								<view class="cart-control">
									<text class="control-btn minus" @click.stop="decrease(dish)"
										:class="{ disabled: getQuantity(dish.id) === 0 }">-</text>
									<text class="quantity" v-if="getQuantity(dish.id) > 0">
										{{ getQuantity(dish.id) }}
									</text>
									<text class="control-btn plus" @click.stop="increase(dish)">+</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载更多提示 -->
				<view class="load-more" v-if="loading">
					<text>加载中...</text>
				</view>
				<view class="load-more" v-else-if="hasMore">
					<text>上拉加载更多</text>
				</view>
				<view class="load-more" v-else>
					<text>没有更多了</text>
				</view>
			</scroll-view>
		</view>

		<!-- 底部购物车栏 -->
		<view class="cart-bar" v-if="totalQuantity > 0">
			<view class="cart-icon" @click="viewCart">
				<text class="icon">🛒</text>
				<text class="badge">{{ totalQuantity }}</text>
			</view>
			<view class="total-info">
				<text class="total-price">¥{{ totalPrice }}</text>
			</view>
			<view class="checkout-btn" @click="goToCheckout">
				<text>去结算</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activeCategory: null, // 当前选中的分类ID
				categories: [], // 分类列表
				dishes: [], // 菜品列表
				cartItems: [], // 购物车商品
				searchKeyword: '', // 搜索关键词
				loading: false, // 加载状态
				hasMore: true, // 是否有更多数据
				currentPage: 1, // 当前页码
				pageSize: 10 // 每页数量
			}
		},
		computed: {
			// 当前选中的分类名称
			activeCategoryName() {
				if (!this.activeCategory) return ''
				const category = this.categories.find(c => c.id === this.activeCategory)
				return category ? category.name : ''
			},
			// 购物车商品总数
			totalQuantity() {
				return this.cartItems.reduce((total, item) => total + item.quantity, 0)
			},
			// 购物车总价
			totalPrice() {
				return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
			}
		},
		methods: {

			async request(url, method = 'GET', data = {}) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:8080' + url, // 根据实际后端地址修改
						method,
						data,
						header: {
							'Content-Type': 'application/json'
						},
						success: (res) => {
							resolve(res.data)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			// 初始化数据
			async initData(clearCart = false) {
				if (clearCart) {
					// 清空购物车
					this.cartItems = [];
					this.saveCartToStorage();
				}

				// 清空分类和菜品数据，确保重新加载
				this.categories = [];
				this.dishes = [];
				this.activeCategory = null;

				await this.loadCategories()
				if (this.categories.length > 0) {
					this.activeCategory = this.categories[0].id
					await this.loadDishes()
				}
			},

			// 加载分类数据
			async loadCategories() {
				try {
					const res = await this.request('/category/list')
					if (res.code === 200) {
						this.categories = res.data || []
					}
				} catch (error) {
					console.error('加载分类失败:', error)
					uni.showToast({
						title: '加载分类失败',
						icon: 'none'
					})
				}
			},

			// 加载菜品数据
			async loadDishes(reset = false) {
				if (this.loading) return

				this.loading = true
				if (reset) {
					this.currentPage = 1
					this.hasMore = true
				}

				try {
					const params = {
						pageNum: this.currentPage,
						pageSize: this.pageSize,
						dish: {
							categoryId: this.activeCategory,
							name: this.searchKeyword
						}
					}

					const res = await this.request('/dish/listPageDish', 'POST', params)

					if (res.code === 200) {
						const newDishes = res.data || []

						if (reset) {
							this.dishes = newDishes
						} else {
							this.dishes = [...this.dishes, ...newDishes]
						}

						this.hasMore = newDishes.length >= this.pageSize
						this.currentPage++
					}
				} catch (error) {
					console.error('加载菜品失败:', error)
					uni.showToast({
						title: '加载菜品失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 选择分类
			selectCategory(categoryId) {
				if (this.activeCategory === categoryId) return

				this.activeCategory = categoryId
				this.loadDishes(true) // 重置加载菜品
			},

			// 处理搜索
			handleSearch(keyword) {
				this.searchKeyword = keyword
				this.loadDishes(true)
			},
			
			//菜品详细页面
			viewDishDetail(dish) {
			  uni.navigateTo({
			    url: `/pages/display/display?dishId=${dish.id}`
			  })
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadDishes()
				}
			},

			// 增加商品数量
			increase(dish) {
				const existingItem = this.cartItems.find(item => item.id === dish.id)
				if (existingItem) {
					existingItem.quantity++
				} else {
					this.cartItems.push({
						...dish,
						quantity: 1,
						selected: true
					})
				}
				this.saveCartToStorage()
			},

			// 减少商品数量
			decrease(dish) {
				const index = this.cartItems.findIndex(item => item.id === dish.id)
				if (index !== -1) {
					if (this.cartItems[index].quantity > 1) {
						this.cartItems[index].quantity--
					} else {
						this.cartItems.splice(index, 1)
					}
					this.saveCartToStorage()
				}
			},

			// 获取商品数量
			getQuantity(dishId) {
				const item = this.cartItems.find(item => item.id === dishId)
				return item ? item.quantity : 0
			},

			// 保存购物车到本地存储
			saveCartToStorage() {
				uni.setStorageSync('cartItems', this.cartItems)
			},

			// 从本地存储加载购物车
			loadCartFromStorage() {
				const savedCart = uni.getStorageSync('cartItems')
				if (savedCart) {
					this.cartItems = savedCart
				}
			},

			// 查看购物车
			viewCart() {
				uni.switchTab({
					url: '/pages/cart/cart'
				})
			},

			// 去结算（预留空位，暂不实现）
			goToCheckout() {
				console.log('去结算功能实现中')
				uni.switchTab({
					url: '/pages/cart/cart'
				})
			}
		},
		onLoad() {
			this.loadCartFromStorage()
			this.initData(true)
		},
		onShow() {
			// 页面显示时刷新购物车数据
			this.loadCartFromStorage()
		}
	}
</script>

<style lang="scss" scoped>
	.classify-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}

	.content-layout {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.category-sidebar {
		width: 30%;
		background-color: #f8f8f8;
		height: 100%;
	}

	.category-item {
		padding: 30rpx 20rpx;
		text-align: center;
		border-bottom: 1rpx solid #eee;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			background-color: #fff;
			color: #e74c3c;
			font-weight: bold;
			border-left: 4rpx solid #e74c3c;
		}
	}

	.dish-content {
		width: 70%;
		height: 100%;
		padding: 20rpx;
		background-color: #fff;
	}

	.section-header {
		padding: 20rpx 0;
		margin-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.dish-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	.dish-card {
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: transform 0.2s;

		&:active {
			transform: scale(0.98);
		}
	}

	.dish-image {
		width: 100%;
		height: 200rpx;
	}

	.dish-info {
		padding: 20rpx;
	}

	.dish-name {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.dish-desc {
		display: block;
		font-size: 24rpx;
		color: #999;
		margin-bottom: 16rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.dish-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.dish-price {
		font-size: 32rpx;
		color: #e74c3c;
		font-weight: bold;
	}

	.cart-control {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.control-btn {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		background-color: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: bold;

		&.plus {
			background-color: #e74c3c;
			color: #fff;
		}

		&.minus {
			color: #666;
		}

		&.disabled {
			opacity: 0.5;
		}
	}

	.quantity {
		font-size: 28rpx;
		font-weight: bold;
		min-width: 40rpx;
		text-align: center;
	}

	.load-more {
		text-align: center;
		padding: 30rpx;
		color: #999;
		font-size: 24rpx;
	}

	.cart-bar {
		height: 100rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.cart-icon {
		position: relative;
		margin-right: 20rpx;

		.icon {
			font-size: 48rpx;
		}

		.badge {
			position: absolute;
			top: -10rpx;
			right: -10rpx;
			background-color: #e74c3c;
			color: #fff;
			border-radius: 50%;
			width: 36rpx;
			height: 36rpx;
			text-align: center;
			line-height: 36rpx;
			font-size: 20rpx;
		}
	}

	.total-info {
		flex: 1;

		.total-price {
			font-size: 32rpx;
			font-weight: bold;
			color: #e74c3c;
		}
	}

	.checkout-btn {
		background-color: #e74c3c;
		color: #fff;
		padding: 20rpx 40rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: bold;
	}
</style>